package com.ztmao.shortlink.project.toolkit;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 *
 * 幂等工具类
 */
@Component
@RequiredArgsConstructor
public class IdempotentUtil {
    private final StringRedisTemplate stringRedisTemplate;
    private final String idempotentKey = "short-link:idempotent:%s";
    private final Integer EXPIRE_TIME = 2*60; // 2分钟过期
    private final String CONSUMING = "0";
    private final String ACCOMPLISH = "1";
    /**
     * 设置消息消费标识，标识不存在则设置为消费中
     * @param messageId 消息ID
     * @return true 设置成功 false 设置失败
     */
    public Boolean setIdentification(String messageId){
        return Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(String.format(idempotentKey, messageId)
                ,"0",EXPIRE_TIME, TimeUnit.SECONDS));
    }

    /**
     *判断消息是否消费完成
     * @param messageId 消息ID
     * @return true 消费完成 false 消费中
     */
    public Boolean isAccomplish(String messageId){
        return ACCOMPLISH.equals(stringRedisTemplate.opsForValue().get(String.format(idempotentKey, messageId)));
    }

    /**
     * 设置消息消费完成
     * @param messageId  消息ID
     *
     */
    public void setAccomplish(String messageId){
         stringRedisTemplate.opsForValue().set(String.format(idempotentKey, messageId),ACCOMPLISH,EXPIRE_TIME, TimeUnit.SECONDS);
    }

    /**
     * 删除消息消费标识
     * @param messageId 消息ID
     */
    public void deleteIdentification(String messageId){
        stringRedisTemplate.delete(String.format(idempotentKey, messageId));
    }
}
